package com.tiantian.web.controller.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tiantian.bean.PageBean;
import com.tiantian.cache.RegionalInformationCache;
import com.tiantian.domain.Ordersstepattach;
import com.tiantian.domain.Orderssteps;
import com.tiantian.domain.Taskinfobasecommission;
import com.tiantian.domain.Taskinformation;
import com.tiantian.domain.Taskproductinformation;
import com.tiantian.poi.PoiReportBuilder;
import com.tiantian.ret.Result;
import com.tiantian.service.BackstagelogService;
import com.tiantian.service.TaskinfobasecommissionService;
import com.tiantian.service.TaskinformationService;
import com.tiantian.service.TaskproductinformationService;
import com.tiantian.service.TasksOrdersService;
import com.tiantian.service.TaskselectvalueaddedservicesService;
import com.tiantian.util.CommonConstant;
import com.tiantian.util.PageUtil;
import com.tiantian.web.controller.task.TaskVo;
import com.tiantian.web.datatables.DataTableReturn;

/**
 * 订单管理
 * 
 */
@Controller
@RequestMapping("/order")
public class OrderController {
	public static final Logger LOG = LoggerFactory.getLogger(OrderController.class);
	@Autowired
	private TasksOrdersService tasksOrdersService;
	@Autowired
	private TaskinformationService taskInfoService;
	@Autowired
	private TaskproductinformationService taskproductinformationService;
	@Autowired
	private RegionalInformationCache regionalInformationCache;
	@Autowired
	private TaskinfobasecommissionService taskinfobasecommissionService;
	@Autowired
	private TaskselectvalueaddedservicesService taskselectvalueaddedservicesService;
	@Autowired
	private BackstagelogService backstagelogService;

	/**
	 * 订单管理
	 * 
	 * @param tipBuyersNotes
	 * @return
	 */
	@RequestMapping(value = { "/index" })
	public void index(Model model, TasksOrdersVo search) {
		model.addAttribute("search", search);
	}

	@ResponseBody
	@RequestMapping(value = { "tasksOrdersList" })
	public Object tasksOrdersList(TasksOrdersVo tasksOrdersVo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(tasksOrdersVo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Map<String, Object>> data = tasksOrdersService.list(params, page);
		return new DataTableReturn(page.getDraw(), page.getTotal(), page.getTotal(), data);
	}

	@RequestMapping(value = { "/detail/{id}" })
	public String detail(Model model, @PathVariable("id") String id, HttpServletRequest request) {
		// 订单信息
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = new HashMap<String, String>();
		params.put("selectOrderid", id);
		List<Map<String, Object>> data = tasksOrdersService.list(params, page);
		if (data.size() > 0) {
			Map<String, Object> order = data.get(0);
			order.put("orderstatus", String.valueOf((char) order.get("orderstatus")));
			model.addAttribute("order", order);
			// BigDecimal principal = ((BigDecimal)
			// order.get("orderprincipal")).add((BigDecimal)
			// order.get("basiscommission"))
			// .add((BigDecimal)
			// order.get("valueaddedservicescommission")).add((BigDecimal)
			// order.get("makeupamount"))
			// .add((BigDecimal) order.get("postage"));
			// model.addAttribute("principal", principal);
			// 地区信息
			String areacode = (String) order.get("areacode");
			model.addAttribute("productin_area", regionalInformationCache.getAreaName(areacode));

			// 任务信息
			String taskId = (String) order.get("taskid");
			Taskinformation taskinfo = taskInfoService.get(taskId);
			model.addAttribute("task", taskinfo);

			// 获取商品列表
			List<Taskproductinformation> productins = taskproductinformationService.findMajorByTaskId(taskId);
			model.addAttribute("productin", productins.get(0));

			// 附属商品
			List<Taskproductinformation> not_main_productins = taskproductinformationService.findMajorNotMainByTaskId(taskId);
			model.addAttribute("productin_not", not_main_productins);

			// 基础佣金
			List<Taskinfobasecommission> basecommissions = taskinfobasecommissionService.findByTaskId(taskId);
			if (basecommissions != null && basecommissions.size() > 0) {
				model.addAttribute("basecommission", basecommissions.get(0));
			}

			// 获取增值服务
			model.addAttribute("taskAddedservics", taskselectvalueaddedservicesService.getByTaskId(taskId));
			// 订单步骤
			List<Orderssteps> orderssteps = tasksOrdersService.getOrdersSteps(id);
			model.addAttribute("orderssteps", orderssteps);
		}
		// 获取订单步骤详情
		Map<String, List<Ordersstepattach>> ordersstepattachMap = tasksOrdersService.getOrdersStepAttachs(id);
		model.addAttribute("ordersstepattachMap", ordersstepattachMap);
		return "/order/detail";
	}

	@RequestMapping(value = { "/reportOrder" })
	public ModelAndView reportTask(TaskVo taskVo, HttpServletRequest request, HttpServletResponse response) {

		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(taskVo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		try {
			List<Map<String, Object>> datas = tasksOrdersService.getOrderReport(params, page);
			PoiReportBuilder builder = new PoiReportBuilder();
			builder.appendHeader("订单ID", "任务ID", "订单状态", "平台", "店铺", "终端", "订单类型", "买手生财ID", "买手账号", "接单时间", "申诉状态", "实际付给买手本金", "实际支付基础佣金",
					"实际支付增值服务佣金");
			if (datas != null) {
				for (Map<String, Object> data : datas) {
					List<String> poiData = new ArrayList<>();
					// "订单ID"
					poiData.add((String) data.get("orderid"));
					// ,"任务ID"
					poiData.add((String) data.get("taskid"));
					// ,"订单状态"
					String orderstatus = String.valueOf(data.get("orderstatus"));
					if (StringUtils.equals(orderstatus, "1")) {
						poiData.add("已发布(待接单)");
					} else if (StringUtils.equals(orderstatus, "2")) {
						poiData.add("已接单(待操作)");
					} else if (StringUtils.equals(orderstatus, "3")) {
						poiData.add("已操作(待确认金额)");
					} else if (StringUtils.equals(orderstatus, "4")) {
						poiData.add("已确认金额(待返款)");
					} else if (StringUtils.equals(orderstatus, "5")) {
						poiData.add("已返款(待评价)");
					} else if (StringUtils.equals(orderstatus, "6")) {
						poiData.add("已评价(待审核)");
					} else if (StringUtils.equals(orderstatus, "7")) {
						poiData.add("已完成");
					} else {
						poiData.add("已撤销");
					}
					// ,"平台"
					String platformid = String.valueOf(data.get("platformid"));
					if (StringUtils.equals(platformid, "1")) {
						poiData.add("淘宝/天猫");
					} else if (StringUtils.equals(platformid, "2")) {
						poiData.add("京东");
					} else {
						poiData.add("其他");
					}
					// ,"店铺"
					poiData.add((String) data.get("storename"));
					// ,"终端",
					String terminalid = String.valueOf(data.get("terminalid"));
					if (StringUtils.equals(terminalid, "1")) {
						poiData.add("PC");
					} else if (StringUtils.equals(terminalid, "2")) {
						poiData.add("手机");
					} else {
						poiData.add("其他");
					}
					// "订单类型",
					poiData.add((String) data.get("tasktypename"));
					// "买手生财ID",
					poiData.add((String) data.get("buyersuserid"));
					// "买手账号",
					poiData.add((String) data.get("platformaccount"));
					// "接单时间",
					poiData.add(DateFormatUtils.format((Date) data.get("orderstime"), CommonConstant.TIME_FORMAT_YMDHMS));
					// "申诉状态"
					String appealsstatus = String.valueOf(data.get("appealsstatus"));
					if (StringUtils.equals(appealsstatus, "0")) {
						poiData.add("等待处理");
					} else if (StringUtils.equals(appealsstatus, "1")) {
						poiData.add("协商中");
					} else if (StringUtils.equals(appealsstatus, "2")) {
						poiData.add("平台介入");
					} else if (StringUtils.equals(appealsstatus, "3")) {
						poiData.add("已完结");
					} else {
						poiData.add("无");
					}
					// ,"实际付给买手本金",
					poiData.add(String.valueOf(((BigDecimal) data.get("orderprincipal")).add((BigDecimal) data.get("basiscommission"))
							.add((BigDecimal) data.get("valueaddedservicescommission")).add((BigDecimal) data.get("makeupamount"))
							.add((BigDecimal) data.get("postage")).doubleValue()));
					// "实际支付基础佣金",
					poiData.add(String.valueOf(((BigDecimal) data.get("basiscommission")).doubleValue()));
					// "实际支付增值服务佣金"
					poiData.add(String.valueOf(((BigDecimal) data.get("valueaddedservicescommission")).doubleValue()));
					builder.appendData(poiData.toArray(new String[poiData.size()]));
				}
			}

			response.reset();// 不加这一句的话会出现下载错误
			String fileName = "订单信息_" + System.currentTimeMillis() + ".xls";
			response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); // 设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 定义输出类型
			builder.write(response.getOutputStream());
			return null;
		} catch (Exception e) {
			LOG.error("导出订单账户异常", e);
			request.setAttribute("message", e.getMessage());
			return new ModelAndView("error.jsp");
		}
	}

	@ResponseBody
	@RequestMapping(value = { "/cancelOrder" })
	public Result<Object> cancelOrder(@RequestParam String orderId) {
		Result<Object> result = tasksOrdersService.cancelOrder(orderId);
		backstagelogService.log("03", orderId, result.isSuccess());
		return result;
	}
}
